//获取应用实例
const app = getApp();
const common = require('../../../utils/common.js');
import { buildTree } from "../../../utils/common";
import { $wuxSelect } from 'weapp'

Page({
    data: {
        optionList:{},
        search_or_filter:1,
        choose_id_arr_list:[],
        choose_id_arr:[],
        choose_cate_name:[],
        choose_index_arr:[],
        active_nav_index:0,
        nav_list:[
            {label:'全部',status:"",field:"all",num:0},
            {label:'待提交',status:10,field:"state",num:0},
            {label:'已提交',status:20,field:"state",num:0},
            {label:'审批中',status:"start",field:"approvelState",num:0},
            {label:'已通过',status:"agree",field:"approvelState",num:0},
            {label:'已拒绝',status:"refuse",field:"approvelState",num:0},
        ],
        material_list:[],
        material_total:0,
        list_params:{
            needPage:true,
            current:1   ,
            size:20,
            pages:0,
            parame:[],
            selectParame:[],
            orderBy:"",
            selectParameter:{
                year:[],
                season:[],
            }
        },
        currentIndex:0
    },

    // 点击菜单
    change_nav: function (events) {
        var index = events.currentTarget.dataset.index;
        let {field} = events.target.dataset
        this.setData({
            ["list_params.selectParameter.state"]:null,
            ["list_params.selectParameter.approvelState"]:null,
        });
        if(field != 'all'){
            this.setData({
                ["list_params.selectParameter."+field]:this.data.nav_list[index]['status'],
            });
        }
        this.setData({
            active_nav_index: index,
        });
        
        // 重新获取数据
        this.getList(1);
    },

    getNavNum(){
        common.request_api('/api/pdm/materialMasterData/getMaterialMasterDataCount',{},true,'get').then(res=>{
            let {nav_list} = this.data
            nav_list.forEach((v)=>{
                v.num = res.data[v.field] || 0
            })
            this.setData({
                nav_list,
            })
        })
    },

    clearPage(){
        this.setData({
            material_list:[],
            ["list_params.current"]:1,
            material_total:0,
        });
    },

    getList(is_clear=0){
        if(is_clear==1){
            this.clearPage();
        }
        let list_params = this.data.list_params
        let max_page = Math.ceil(this.data.material_total/list_params.size);
        
        //没数据了，拦截
        if(this.data.material_total>0 && max_page<list_params.current){
            return;
        }

        let categoryIdList = []
        const choose_id_arr_list = this.data.choose_id_arr_list
        choose_id_arr_list.forEach(item => {
          item.forEach(item2 => {
            const ids = item2.split(',')
            categoryIdList = categoryIdList.concat(ids)
          })
        })
        let uniqueArray = [...new Set(categoryIdList)];
        uniqueArray = uniqueArray.filter(v=>v != '' && v != null && v != 0)
        list_params.selectParameter.cateIds = uniqueArray

        common.request_api("/api/erp/other/makeApplyOrder/queryPageList",this.data.list_params).then((res)=>{
            res.data.records.forEach((v)=>{
                let materialMainImage = v.materialMainImage
                v.materialMainImage =  `${app.globalData.alphaCdnUrl}/${materialMainImage}`;
                if(materialMainImage){
                    v.materialMainImages = [v.materialMainImage];
                }else{
                    v.materialMainImages = [];
                }
               
            })
            let material_list = this.data.material_list
            material_list.push(...res.data.records);
            this.setData({
                material_list:material_list,
                ["list_params.size"]:res.data.size,
                material_total:res.data.total,
                ["list_params.current"]:this.data.list_params.current+1,
            })
        });
    },

    onLoad: function (options) {
        this.getAttrOptions();
        // this.generateYearArray();
        this.getList();
        // this.getNavNum();
        // 设置标题
        wx.setNavigationBarTitle({
            title: '加工申请单列表'
        });
        // 获取分类
        this.get_cate_list();
    },

    // 每次显示时
    onShow() {
        var __this = this;

    },
    onClick3() {
      $wuxSelect('#foo-select3').open({
        value: this.data.value3,
        multiple: true,
        toolbar: {
          title: '季节',
          confirmText: '确定',
        },
        options: [
          {
            title: '春',
            value: '春',
          },
          {
            title: '夏',
            value: '夏',
          },
          {
            title: '秋',
            value: '秋',
          },
          {
            title: '冬',
            value: '冬',
          },
        ],
        onChange: (value, index, options) => {
          console.log('onChange', value, index, options)
          this.setData({
            // value3: value,
            title3: index.map((n) => options[n].title),
          })
        },
        onConfirm: (value, index, options) => {
          this.setData({
            value3: value,
            title3: index.map((n) => options[n].title),
          })
          this.onPullDownRefresh();
        },
      })
    },
    DeleteJijie(e){
      var index = e.currentTarget.dataset.index;
      this.data.value3.splice(index, 1);
      this.setData({
          value3: this.data.value3,
      })
      // 刷新
      this.onPullDownRefresh();
    },
    template_purchase: (e) => {
        let {template_id} = e.currentTarget.dataset;
        wx.navigateTo({
            url: '/pages/material/index?template_id=' + template_id,
        })
    },
    // 页面触底时执行
    onReachBottom: function () {
        this.getList();
    },

    // 监听下拉[刷新]
    onPullDownRefresh: function () {
        this.getList(1);
        // 停止下拉
        setTimeout(() => {
            wx.stopPullDownRefresh();
        }, 1000)
    },


    // 切换展示搜索或者筛选
    search_filter_change: function (events) {
        // this.setData({
        //     search_or_filter: this.data.search_or_filter == 1 ? 2 : 1
        // })
    },

    // 搜索
    GoSearch: function (e) {
        let { field } = e.currentTarget.dataset;
        let value = e.detail.value
        this.setData({
          [field]: value,
        });
        console.log('aaaaaa')
        this.getList(1);
    },

    // 创建样板
    material_add: function (events) {
        var __this = this;
        console.log('aaaaaaaaaaaa')
        // 跳转到创建样板页面
        wx.navigateTo({
            url: '/alpha/pages/alpha_material_form/index?template_id=0',
        });
    },

    // 编辑样板
    template_update: function (events) {
        var index = events.currentTarget.dataset.index;
        var __this = this;
        // 跳转
        wx.navigateTo({
            url: '/alpha/pages/alpha_make_apply_form/index?id=' + __this.data.material_list[index].id,
            events: {
                // 当修改完成时
                changeData: function (data) {

                }
            }
        });
    },

        // 编辑样板
        template_copy: function (events) {
            var index = events.currentTarget.dataset.index;
            var __this = this;
            // 跳转
            wx.navigateTo({
                url: '/alpha/pages/alpha_make_apply_form/index?id=' + __this.data.material_list[index].id + "&isCopy=1",
                events: {
                    // 当修改完成时
                    changeData: function (data) {
    
                    }
                }
            });
        },

    // 跳转到详情页面
    template_detail: function (events) {
        var index = events.currentTarget.dataset.index;
        var __this = this;
        // 跳转
        wx.navigateTo({
            url: '/pages/template_detail/template_detail?template_id=' + __this.data.template_list[index].template_id,
            events: {
                // 当点击生产按钮时
                changeProductData: function (data) {
                    __this.data.template_list[index].status.value = 3;
                    __this.setData({
                        template_list: __this.data.template_list
                    })
                },
                // 当点击关闭生产按钮时
                changeCloseData: function (data) {
                    __this.data.template_list[index].status.value = 99;
                    __this.setData({
                        template_list: __this.data.template_list
                    })
                }
            }
        });
    },

    // 关闭生产
    template_close: function (events) {
        var index = events.currentTarget.dataset.index;
        var __this = this;
        // 确认提示
        wx.showModal({
            title: '提示',
            content: '您确定要关闭生产吗',
            success(res) {
                if (res.confirm) {
                    __this.template_close_request(index);
                }
            },
        });
    },

    // 关闭生产请求
    template_close_request: function (index) {
        var __this = this;
        var template_id = __this.data.template_list[index].template_id;
        var result = app.request_api('admin/template/closeTemplate', {
            id: template_id
        }, true);
        result.then(res => {
            wx.showToast({
                title: '已关闭生产',
                icon: 'none',
                duration: 2000,
            });
            // 将此数据从列表删除
            __this.data.template_list.splice(index, 1);
            __this.setData({
                template_list: __this.data.template_list
            });
        });
    },

    // 删除
    submitMakeApply: function (events) {
        var index = events.currentTarget.dataset.index;
        var __this = this;
        // 确认提示
        wx.showModal({
            title: '提示',
            content: '您确定要提交此申请单吗',
            success(res) {
                if (res.confirm) {
                    var id = __this.data.material_list[index].id;
                    var result = common.request_api("/api/erp/other/makeApplyOrder/submit",{ids:[id]}).then((res)=>{
                        wx.showToast({
                            title: res.msg,
                            icon: 'none',
                            duration: 2000,
                        });
                    });
                }
            },
        });
    },

        // 删除
        resubmitMakeApply: function (events) {
            var index = events.currentTarget.dataset.index;
            var __this = this;
            // 确认提示
            wx.showModal({
                title: '提示',
                content: '您确定要提交此申请单吗',
                success(res) {
                    if (res.confirm) {
                        var id = __this.data.material_list[index].id;
                        var result = common.request_api("/api/erp/other/makeApplyOrder/reSubmit",{ids:[id]}).then((res)=>{
                            wx.showToast({
                                title: res.msg,
                                icon: 'none',
                                duration: 2000,
                            });
                        });
                    }
                },
            });
        },

    // 删除样板请求
    submitMakeApplyRequest: function (index) {
        var __this = this;
    
      
    },

    // 确认生产
    template_product: function (events) {
        var index = events.currentTarget.dataset.index;
        var __this = this;
        // 确认提示
        wx.showModal({
            title: '提示',
            content: '您确定要开始生产吗',
            success(res) {
                if (res.confirm) {
                    __this.template_product_request(index);
                }
            },
        });
    },

    // 确认生产请求
    template_product_request: function (index) {
        var __this = this;
        var template_id = __this.data.template_list[index].template_id;
        var result = app.request_api('admin/template/postConfirmProduct', {
            template_id: template_id
        }, true);
        result.then(res => {
            wx.showToast({
                title: '已开始生产',
                icon: 'none',
                duration: 2000,
            });
            // 修改状态
            __this.data.template_list[index].status.value = 3;
            __this.setData({
                template_list: __this.data.template_list
            });
        });
    },

    // 预览图片
    PreviewImg: function (events) {
        var pic_arr = events.currentTarget.dataset.pic;
        // 调用
        wx.previewImage({
            current: pic_arr[0], // 当前显示图片的http链接
            urls: pic_arr // 需要预览的图片http链接列表
        })
    },

    // 生成年份
    generateYearArray: function () {
        var currentYear = new Date().getFullYear();
        var pastYears = 7;
        var futureYears = 3;
        var yearArray = [];
        // 生成过去7年的年份
        for (var i = currentYear - pastYears; i <= currentYear; i++) {
            yearArray.push(i);
        }
        // 生成未来3年的年份
        for (var j = currentYear + 1; j <= currentYear + futureYears; j++) {
            yearArray.push(j);
        }
        var currentIndex = pastYears;
        // 更新数据
        this.setData({
            yearArray: yearArray,
            currentIndex: currentIndex
        });
    },

    // 年份改变时
    yearChange: function (event) {
        var selectedYear = this.data.optionList.yearList[event.detail.value].value;
        // 验证是否在数组中
        if (this.data.list_params.selectParameter.year.findIndex(obj => obj === selectedYear) > -1) {
            wx.showToast({
                title: '已选择过此年份',
                icon: 'none',
                duration: 1500,
            });
            return false;
        }
        this.data.list_params.selectParameter.year.push(selectedYear)
        this.setData({
            year: this.data.list_params.selectParameter.year,
        });
        // 刷新
        this.onPullDownRefresh();
    },

        // 年份改变时
        seasonChange: function (event) {
            var selectedYear = this.data.optionList.seasonList[event.detail.value].value;
            // 验证是否在数组中
            if (this.data.list_params.selectParameter.season.findIndex(obj => obj === selectedYear) > -1) {
                wx.showToast({
                    title: '已选择过此季节',
                    icon: 'none',
                    duration: 1500,
                });
                return false;
            }
            this.data.list_params.selectParameter.season.push(selectedYear)
            this.setData({
                season: this.data.list_params.selectParameter.season,
            });
            // 刷新
            this.onPullDownRefresh();
        },

    // 选择类型时
    dataTypeChage: function (e) {
        this.setData({
            data_type_name: this.data.data_type_list[e.detail.value].name,
            data_type_value: this.data.data_type_list[e.detail.value].value,
        });
        // 刷新
        this.onPullDownRefresh();
    },

    // 获取分类
    get_cate_list: function () {
        // 发起请求
        var result = app.request_api('admin/processTemplate/get_category_list', {
            is_mini: 1
        }, false);
        result.then(res => {
            // console.log(res);
            if (res.list.length > 0) {
                res.list.forEach(function (item, index) {
                    // 往子项里追加全部
                    res.list[index].children.unshift({
                        id: 0,
                        category_name: '全部',
                        children: [],
                    });
                    res.list[index].children.forEach(function (item2, index2) {
                        res.list[index].children[index2].children.unshift({
                            id: 0,
                            category_name: '全部'
                        });
                    });
                });
                this.setData({
                    cate_show_data: [res.list, res.list[0].children, res.list[0].children[0].children],
                    cate_all_data: res.list
                });
            }
        });
    },
// 获取分类
get_cate_list: function () {
    // 发起请求
    var result = common.request_api('/api/bamboo/pdCategory/listAll', {}, false, 'GET');
    result.then(res => {
        const tree = buildTree(res.data)
        if (tree.length > 0) {
            tree.forEach(function (item, index) {
                // 往子项里追加全部

                // 二级的全部，塞入二级所有id
                const id = item.children.map(p => p.id).join(',')
                item.children.unshift({
                    id: id,
                    cnName: '全部',
                    children: [],
                    pp_id:0
                });

                // 收集全部下的全部 == 当前一级分类下面的所有三级分类集合
                let allIds = [];
                item.children.forEach((item2,index2)=>{
                    const id = item2.children.map(p => p.id);
                    allIds = allIds.concat(id);
                });
               
                item.children.forEach((item2,index2)=>{
                     // 当前二级分类所有id
                     const id = item2.children.map(p => p.id)

                     let setId = [];
                    if(item2.cnName == '全部'){
                        setId = allIds
                    }else{
                        setId = id
                    }
                    item2.children.unshift({
                        id: setId.join(","),
                        cnName: '全部',
                        pp_id:0
                    });
                })
            });
            this.setData({
                cate_show_data: [tree, tree[0].children, tree[0].children[0].children],
                cate_all_data: tree,
                cata_list :res.data
            });
        }
    });
},
// 分类值变化时
    CateValueChange: function (e) {
        var cate_show_data = this.data.cate_show_data;
        var choose_index_arr = e.detail.value;
        let choose_cate_name = ''
        let isIds = []
        choose_index_arr.forEach((item, index) => {
          const id = cate_show_data[index][item].id
          if (index !== choose_index_arr.length - 1) {
            choose_cate_name += cate_show_data[index][item].cnName + ' - '
          } else {
            choose_cate_name += cate_show_data[index][item].cnName
          }
          isIds.push(cate_show_data[index][item].id)
        })
        let choose_id_arr_list = this.data.choose_id_arr_list || []
        let flag = this.data.choose_id_arr_list.find( i => JSON.stringify(i) === JSON.stringify(isIds))
        if (flag) {
          wx.showToast({
            title: '该分类条件已存在',
            icon: 'error',
            duration: 2000,
          });
          return
        }
        choose_id_arr_list.push(isIds)
        // var choose_cate_name = cate_show_data[0][choose_index_arr[0]].cnName + ' - ' + cate_show_data[1][choose_index_arr[1]].cnName + ' - ' + cate_show_data[2][choose_index_arr[2]].cnName;
        // 更新值
        this.data.choose_id_arr.push(isIds);
        this.data.choose_cate_name.push(choose_cate_name);
        this.data.choose_index_arr.push(choose_index_arr);
        let arr = new Array()
        for (const item of this.data.choose_id_arr) {
            if (item[0] == 0 && item[1] == 0 && item[2] == 0) {
                arr = new Array()
                break;
            }
            if (item[0] != 0 && item[1] != 0 && item[2] != 0) {
                arr.push(item[2])
            }
            if (item[0] != 0 && item[1] == 0  && item[2] == 0) {
                for (const cate_item of this.data.cate_all_data) {
                    if (cate_item.id != item[0]) {
                        continue;
                    }
                    for (const son of cate_item.children) {
                        for (const da of son.children) {
                            if (da.id > 0) {
                                arr.push(da.id)
                            }
                        }
                    }
                }
            }
            if (item[0] != 0 && item[1] != 0  && item[2] == 0) {
                for (const cate_item of this.data.cate_all_data) {
                    if (cate_item.id != item[0]) {
                        continue;
                    }
                    for (const son of cate_item.children) {
                        if (son.id != item[1]) {
                            continue;
                        }
                        for (const da of son.children) {
                            if (da.id > 0) {
                                arr.push(da.id)
                            }
                        }
                    }
                }
            }
        }
        this.setData({
            choose_id_arr: arr,
            choose_index_arr: this.data.choose_index_arr,
            choose_cate_name: this.data.choose_cate_name,
            choose_id_arr_list
        });
        // 刷新
        this.onPullDownRefresh();
    },
// 分类列变化时
CateColumnChange: function (e) {
    var cate_all_data = this.data.cate_all_data;
    var cate_show_data = this.data.cate_show_data;
    var sel_index_arr = this.data.sel_index_arr;
    var index = e.detail.value;
    if (e.detail.column == 0) {
        // 一级分类改变时
        this.data.cate_show_data[1] = cate_all_data[index].children;
        this.data.cate_show_data[2] = cate_all_data[index].children[0].children;
        sel_index_arr = [index, 0, 0];
    }
    if (e.detail.column == 1) {
        // 二级分类改变时
        this.data.cate_show_data[2] = cate_show_data[1][index].children;
        sel_index_arr[1] = index;
        sel_index_arr[2] = 0;
    }
    if (e.detail.column == 2) {
        // 三级分类改变时
        sel_index_arr[2] = index;
    }
    // 重新渲染
    this.setData({
        cate_show_data: this.data.cate_show_data,
        sel_index_arr: sel_index_arr
    });
},

    // 删除年份
    deleteResult: function (e) {
        let {field,index} = e.currentTarget.dataset
        // 删除对应年份
        this.data[field].splice(index, 1);
        this.setData({
            [field]: this.data[field],
        })
        // 刷新
        this.onPullDownRefresh();
    },
    getAttrOptions(){
        var nameToField = {
          "年份": "yearList",
          "季节": "seasonList",
          "波段": "bdList"
        };
        common.request_api('/api/bamboo/pdAttribute/listByAttributeName',Object.keys(nameToField),true,'post').then(res=>{
            let optionList = this.data.optionList
          res.data.forEach((v, k) => {
            optionList[nameToField[v.name]] = v.attributeValueList || []
          })
          this.setData({
              yearCurrentIndex:optionList.yearList.length - 1,
            optionList:optionList
          })
        }).finally(() => {
        })
      },

    // 删除分类
    DeleteCategory: function (e) {
        var index = e.currentTarget.dataset.index;
        const choose_id_arr_list = this.data.choose_id_arr_list
        choose_id_arr_list.splice(index, 1);
        this.data.choose_id_arr.splice(index, 1);
        this.data.choose_index_arr.splice(index, 1);
        this.data.choose_cate_name.splice(index, 1);
        this.setData({
            choose_id_arr: this.data.choose_id_arr,
            choose_index_arr: this.data.choose_index_arr,
            choose_cate_name: this.data.choose_cate_name,
            choose_id_arr_list
        })
        // 刷新
        this.onPullDownRefresh();
    },

    // 删除品牌
    DeleteType: function () {
        this.setData({
            data_type_value: 0,
            data_type_name: '',
        })
        // 刷新
        this.onPullDownRefresh();
    },

})
